<template>
	<div>
		<el-table :data="searchs(search)" v-loading="loading" style="width: 100%" max-height="580">
			<el-table-column type="expand">
				<template slot-scope="props">
					<el-form label-position="left" inline class="demo-table-expand">
						<el-form-item label="用户邮箱:">
							<a :href="`mailto:${props.row.email}`">{{ props.row.email }}</a>
						</el-form-item>
						<el-form-item label="是否员工:">
							<span>{{ props.row.is_staff?'是':'否' }}</span>
						</el-form-item>
						<el-form-item label="活跃状态:">
							<span>{{ props.row.is_active?'是':'否' }}</span>
						</el-form-item>
						<el-form-item label="性别:">
							<span>{{ props.row.sex?'男':'女' }}</span>
						</el-form-item>
						<el-form-item label="年龄:">
							<span>{{ props.row.age }}</span>
						</el-form-item>
						<el-form-item label="头像:">
							<span style="display:inline-block;width:50px;height:50px;">
								<img style="width:100%;height:100%" :src="props.row.icon" alt />
							</span>
						</el-form-item>
						<el-form-item label="所属分组:">
							<span v-for="(item, index) in props.row.groups" :key="index">[ {{ item.name }} ]</span>
						</el-form-item>
						<el-form-item label="拥有权限:">
							<span v-for="(item, index) in props.row.user_permissions" :key="index">[ {{ item.name }} ]</span>
						</el-form-item>
					</el-form>
				</template>
			</el-table-column>
			<el-table-column label="ID" sortable width="80" prop="id"></el-table-column>
			<el-table-column align="center" width="140" label="用户名" prop="username"></el-table-column>
			<el-table-column align="center" sortable width="140" label="上次登陆" prop="last_login">
				<template slot-scope="scope">
					<span>{{scope.row.last_login | alltime}}</span>
				</template>
			</el-table-column>
			<el-table-column align="center" sortable width="140" label="注册日期" prop="date_joined">
				<template slot-scope="scope">
					<span>{{scope.row.date_joined | alltime}}</span>
				</template>
			</el-table-column>
			<el-table-column align="center" label="电话" prop="mobile"></el-table-column>
			<el-table-column align="center" label="部门">
				<template slot-scope="scope">
					<span>{{scope.row.depar==null?'':scope.row.depar.depar_name }}</span>
				</template>
			</el-table-column>
			<el-table-column align="left" width="250">
				<template slot="header" slot-scope="scope">
					<div style="display:flex;">
						<span style="dispaly:none">{{scope.row}}</span>
						<el-input v-model="search" size="mini" placeholder="输入用户名搜索" />
						<el-button
							v-if="canAdd"
							type="success"
							size="mini"
							@click="handleAdd(scope.$index, scope.row)"
						>新增</el-button>
					</div>
				</template>
				<template slot-scope="scope">
					<el-button
						v-if="canEdit"
						type="primary"
						size="mini"
						@click="handleEdit(scope.$index, scope.row)"
					>编辑</el-button>

					<el-popover placement="top" width="160" v-model="scope.row.color">
						<p>这是一个正在使用的账号,确定删除吗？</p>
						<div style="text-align: right; margin: 0">
							<el-button size="mini" type="text" @click="scope.row.color = false">取消</el-button>
							<el-button type="primary" size="mini" @click="deactivate(scope.row,scope.$index)">确定</el-button>
						</div>
						<el-button
							slot="reference"
							v-if="user_infos.id!=scope.row.id && canDelete"
							size="mini"
							type="danger"
							@click="handleDelete(scope.$index, scope.row)"
						>禁用</el-button>
					</el-popover>
				</template>
			</el-table-column>
		</el-table>
		<!-- 新增用户弹框 -->
		<el-dialog
			title="新增用户"
			:before-close="handleClose"
			:visible.sync="centerDialogVisible"
			width="38%"
			center
		>
			<el-form
				:model="ruleForm"
				status-icon
				:rules="rules"
				ref="ruleForm"
				label-width="80px"
				class="demo-ruleForm"
			>
				<el-form-item label="账号" prop="name">
					<el-input type="text" v-model="ruleForm.name" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="pass">
					<el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="确认密码" prop="pass2">
					<el-input type="password" v-model="ruleForm.pass2" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="phone">
					<el-input type="text" v-model="ruleForm.phone" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input type="text" v-model="ruleForm.email" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="超管">
					<el-switch v-model="is_super_user" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
				</el-form-item>
				<el-form-item label="员工">
					<el-switch v-model="is_staff" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
				</el-form-item>
				<el-form-item label="账户状态">
					<el-switch v-model="is_active" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
				</el-form-item>
				<el-form-item>
					<div class="btns">
						<el-button size="small" type="success" @click="submitForm('ruleForm')">新增</el-button>
						<el-button size="small" type="danger" @click="resetForm('ruleForm')">重置</el-button>
					</div>
				</el-form-item>
			</el-form>
		</el-dialog>
		<!-- 编辑用户弹框 -->
		<el-dialog
			title="编辑用户"
			:before-close="handleClose"
			:visible.sync="centerDialogVisible2"
			width="38%"
			center
		>
			<el-form
				:model="ruleForm2"
				status-icon
				:rules="rules2"
				ref="ruleForm2"
				label-width="80px"
				class="demo-ruleForm"
			>
				<el-form-item label="用户名" prop="name">
					<el-input type="text" v-model="ruleForm2.name" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="phone">
					<el-input type="text" v-model="ruleForm2.phone" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input type="text" v-model="ruleForm2.email" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item>
					<div class="btns">
						<el-button size="small" type="success" @click="submitForm2('ruleForm2')">保存</el-button>
						<!-- <el-button size="small" type="danger" @click="resetForm('ruleForm')">重置</el-button> -->
					</div>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
export default {
	data() {
		var validatePass = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("请输入密码"));
			} else {
				if (value.length > 5) {
					callback();
				} else {
					callback(new Error("密码太短"));
				}
			}
		};
		var validatePass2 = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("请确认密码"));
			} else {
				if (value !== this.ruleForm.pass) {
					callback(new Error("两次密码不一致"));
				} else {
					callback();
				}
			}
		};
		var validateName = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("请输入账号"));
			} else {
				if (value.length > 10 || value.length < 2) {
					callback(new Error("账号长度在2-10字符"));
				} else {
					callback();
				}
			}
		};
		var validatePhone = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("请输入手机号"));
			} else {
				let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
				if (reg.test(value)) {
					callback();
				} else {
					callback(new Error("请输入合法大陆手机号"));
				}
			}
		};
		var validateEmail = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("请输入邮箱"));
			} else {
				let reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
				if (reg.test(value)) {
					callback();
				} else {
					callback(new Error("请输入正确邮箱"));
				}
			}
		};
		return {
			loading: false,
			search: "",
			tableData: [],
			user_infos: {},
			canDelete: false,
			canEdit: false,
			canAdd: false,
			is_admin: false,
			delete_list: [],
			centerDialogVisible: false,
			visible: true,
			centerDialogVisible2: false,
			is_super_user: false,
			is_active: true,
			is_staff: true,
			ruleForm: {
				pass: "",
				pass2: "",
				name: "",
				phone: "",
				email: ""
			},
			rules: {
				pass: [
					{
						validator: validatePass,
						trigger: "blur"
					}
				],
				pass2: [
					{
						validator: validatePass2,
						trigger: "blur"
					}
				],
				name: [
					{
						validator: validateName,
						trigger: "blur"
					}
				],
				phone: [
					{
						validator: validatePhone,
						trigger: "blur"
					}
				],
				email: [
					{
						validator: validateEmail,
						trigger: "blur"
					}
				]
			},
			ruleForm2: {
				name: "",
				phone: "",
				email: ""
			},
			rules2: {
				name: [
					{
						validator: validateName,
						trigger: "blur"
					}
				],
				phone: [
					{
						validator: validatePhone,
						trigger: "blur"
					}
				],
				email: [
					{
						validator: validateEmail,
						trigger: "blur"
					}
				]
			}
		};
	},
	methods: {
		// 获取用户列表
		get_user_list() {
			this.$ajax
				.get("/user")
				.then(res => {
					let arr = [];
					res.data.results.forEach(item => {
						if (item.is_active) {
							arr.push(item);
						}
					});
					this.tableData = arr;
					let that = this;
					setTimeout(function() {
						that.loading = false;
					}, 200);
				})
				.catch(err => {});
		},
		// ccommon
		get_ids(arr) {
			let res = null;
			if (arr) {
				res = [];
				if (arr.length > 0) {
					arr.forEach(item => {
						res.push(item.id);
					});
				}
			}
			console.log(res);
			return res;
		},
		// 编辑
		handleEdit(index, item) {
			this.centerDialogVisible2 = true;
			this.ruleForm2.name = item.username;
			this.ruleForm2.phone = item.mobile;
			this.ruleForm2.email = item.email;
			this.ruleForm2.id = item.id;

			this.ruleForm2.is_superuser = item.is_superuser;
			this.ruleForm2.is_staff = item.is_staff;
			this.ruleForm2.is_active = item.is_active;

			this.ruleForm2.groups = this.get_ids(item.groups);
			this.ruleForm2.depar = this.get_ids(item.depar);
			this.ruleForm2.user_permissions = this.get_ids(
				item.user_permissions
			);
		},
		// 删除
		handleDelete(index, item) {},
		// 新增
		handleAdd(index, item) {
			this.centerDialogVisible = true;
		},
		// 搜索功能
		searchs(kw) {
			let searchingList = [];
			this.tableData.forEach(item => {
				if (item.username.indexOf(kw) != -1) {
					searchingList.push(item);
				}
			});
			return searchingList;
		},
		submitForm(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					let form = new FormData();
					form.append("username", this.ruleForm.name);
					form.append("password", this.ruleForm.pass);
					form.append("mobile", this.ruleForm.phone);
					form.append("email", this.ruleForm.email);
					form.append("is_superuser", this.is_super_user);
					form.append("is_active", this.is_active);
					form.append("is_staff", this.is_staff);
					this.$ajax
						.post("/user/", form)
						.then(res => {
							console.log(res.data);
							this.tableData.splice(0, 0, res.data);
							this.$message({
								message: "操作成功",
								type: "success"
							});
							this.centerDialogVisible = false;
							// this.resetForm("ruleForm");
						})
						.catch(err => {
							this.$message({
								message: "操作失败",
								type: "info"
							});
						});
				} else {
					return false;
				}
			});
		},
		submitForm2(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					let form = new FormData();
					form.append("username", this.ruleForm2.name);
					form.append("email", this.ruleForm2.email);
					form.append("mobile", this.ruleForm2.phone);
					if (this.is_admin) {
						form.append(
							"is_superuser",
							this.ruleForm2.is_superuser
						);
						form.append("is_staff", this.ruleForm2.is_staff);
						form.append("is_active", this.ruleForm2.is_active);
						if (this.ruleForm2.groups) {
							if (this.ruleForm2.groups.length > 0) {
								this.ruleForm2.groups.forEach(item => {
									form.append("groups", item);
								});
							}
						}
						if (this.ruleForm2.depar) {
							if (this.ruleForm2.depar.length > 0) {
								this.ruleForm2.depar.forEach(item => {
									form.append("depar", item);
								});
							}
						}
						if (this.ruleForm2.user_permissions) {
							if (this.ruleForm2.user_permissions.length > 0) {
								this.ruleForm2.user_permissions.forEach(item => {
										form.append("user_permissions", item);
									}
								);
							}
						}
					}
					this.$ajax
						.put("/user/" + this.ruleForm2.id + "/", form)
						.then(res => {
							console.log(res.data);
							this.$message({
								message: "操作成功",
								type: "success"
							});
							this.centerDialogVisible2 = false;
							this.tableData.forEach((item, index) => {
								if (item.id == this.ruleForm2.id) {
									this.tableData[index] = res.data;
									return false;
								}
							});
						})
						.catch(err => {
							this.$message({
								message: "操作失败",
								type: "info"
							});
						});
				} else {
					return false;
				}
			});
		},
		resetForm(formName) {
			this.$refs[formName].resetFields();
			this.ramdomColor();
		},
		handleClose(done) {
			this.$confirm("确认关闭？")
				.then(_ => {
					// this.resetForm("ruleForm");
					done();
				})
				.catch(_ => {});
		},
		// 确认禁用
		deactivate(item, index) {
			let form = new FormData();
			form.append("username", item.username);
			form.append("email", item.email);
			form.append("mobile", item.mobile);
			if (this.is_admin) {
				form.append("is_superuser", item.is_superuser);
				form.append("is_staff", item.is_staff);
				form.append("is_active", false);
				if (item.groups) {
					if (item.groups.length > 0) {
						this.get_ids(item.groups).forEach(items=>{
							form.append("groups", items);
						})
					}
				}
				if (item.depar) {
					if (item.depar.length > 0) {
						this.get_ids(item.depar).forEach(items=>{
							form.append("depar", items);
						})
					}
				}
				if (item.user_permissions) {
					if (item.user_permissions.length > 0) {
						this.get_ids(item.user_permissions).forEach(items=>{
							form.append("user_permissions",items);
						})
					}
				}
			}
			this.$ajax
				.put("/user/" + item.id + "/", form)
				.then(res => {
					this.tableData.splice(index, 1);
					this.$message({
						message: "操作成功",
						type: "success"
					});
					item.color = false;
				})
				.catch(err => {
					this.$message({
						message: "操作失败",
						type: "info"
					});
				});
		}
	},
	mounted() {
		this.loading = true;
		this.get_user_list();
		this.user_infos = JSON.parse(window.localStorage.getItem("user"));
		if (this.user_infos.groups.length > 0) {
			this.user_infos.groups.forEach(item => {
				if (item.name == "管理员") {
					this.is_admin = true;
					this.canDelete = true;
					return false;
				}
			});
		}
		if (this.user_infos.user_permissions.length > 0) {
			// this.user_infos.user_permissions.forEach(item => {
			// 	if (item.codename == "delete_user") {
			// 		this.canDelete = true;
			// 		return false;
			// 	}
			// });
			this.user_infos.user_permissions.forEach(item => {
				if (item.codename == "change_user") {
					this.canEdit = true;
					return false;
				}
			});
			this.user_infos.user_permissions.forEach(item => {
				if (item.codename == "add_user") {
					this.canAdd = true;
					return false;
				}
			});
		}
	}
};
</script>


<style lang="scss" scoped>
.demo-table-expand {
	font-size: 0;
}
.demo-table-expand label {
	width: 90px;
	color: #99a9bf;
}
.demo-table-expand .el-form-item {
	margin-right: 0;
	margin-bottom: 0;
	width: 50%;
}
</style>